#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using TVC.Layout;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using QueryBuilder;
using TVC.Report;
using FlexCel.Core;
using System.IO;

#endregion

namespace TVC.Modules.Ref
{
    public partial class Categories : ModuleParent, IHostedApplication
    {

        int idAllowEditLanguage = 1;
        int idAddNew = 115;
        int idEdit = 116;
        int idDelete = 117;
        int idTransferIn = 118;
        int idTransferOut = 119;
        int idPrint = 120;
        int idExcel = 242;
        GridLayout layout = null;
        string TB = "TVC_RFITM";
        string TBField = "Category";
        string strAction = "";

        DTO.PODInfo PODInfo;
        private DataTable _dtb;
        //BUS.TVC_LOOKUPControl lkctr = new BUS.TVC_LOOKUPControl();
        public Categories()
        {
            _strType = "Categories";
            InitializeComponent();
            _dgvList = dgvList;
            _dgvFilter = gridFilter1;
            PODInfo = (DTO.PODInfo)Session["USER"];
            //lkctr.business = PODInfo.Business_ID;
        }

        public void InitializeApplication()
        {
        }

        //public void AddNew()
        //{

        //}

        public void SetObject(object obj)
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idEdit))
                objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            if (IsPermis(idAddNew))
                objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O"));
            if (IsPermis(idAddNew) && IsPermis(idEdit))
                objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S"));
            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idDelete))
                objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));
            if (IsPermis(idTransferIn))
                objElements.Add(new HostedToolBarButton("Transfer In", "Import", new IconResourceHandle("Down.png"), "TI", false));
            if (IsPermis(idTransferOut))
                objElements.Add(new HostedToolBarButton("Transfer Out", "Export", new IconResourceHandle("Up.png"), "TO", false));
            if (IsPermis(idTransferOut))
                objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Up.png"), "TX"));
            if (IsPermis(idExcel)) objElements.Add(new HostedToolBarButton("Tree View to Excel", "Tree View to Excel", new IconResourceHandle("Excel.png"), "E"));
            objElements.Add(new HostedToolBarButton("Refresh", "Refresh", new IconResourceHandle("Refresh.png"), "R", false));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }
        protected override void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;

            switch (strAction)
            {
                case "C":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TI") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TO") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TX") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
                case "A":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TI") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TO") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TX") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
                case "S":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TI") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TO") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TX") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;

                case "O":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TI") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TO") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TX") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
                case "V":
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TI") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TO") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "TX") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "R") { button.Enabled = on; break; } }
                    foreach (ToolBarButton button in tbarLocal.Buttons) { if (button.Name == "K") { button.Enabled = on; break; } }
                    break;
            }

        }
        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            try
            {
                sErr = "";
                strAction = (string)objButton.Tag;

                BUS.TVC_LOOKUPControl ctr = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
                switch (strAction)
                {
                    case "K":
                        skip();
                        break;
                    case "C":
                        AddNew(txtCode);
                        break;
                    case "A":
                        editRecord(txtCode);
                        break;
                    case "S":
                        saveRecord(txtCode, false);

                        break;
                    case "O":
                        copy(txtCode);
                        break;
                    case "X":
                        delete(txtCode);
                        break;
                    case "TI":
                        Forms.frmTransferIn frmTI = new Forms.frmTransferIn(_strType, GetMainForm());
                        frmTI.ShowDialog();
                        break;
                    case "TO":
                        export2Xml();
                        break;
                    case "TX":
                        export2Excel();
                        break;
                    case "R":
                        reloadList();
                        break;
                    case "E":
                        {

                            SQLBuilder _sql = SQLBuilder.LoadSQLBuilderFromDataBase("ItemCate01_" + GetMainForm().PODInfo.Business_ID, "TVC", "");

                            //_sql.Filters[0].ValueFrom = "ZZZ";
                            //_sql.Filters[0].FilterFrom = "ZZZ";
                            //_sql.Filters[0].ValueTo = "";

                            ReportGenerator.User2007 = false;
                            ReportGenerator _report = new ReportGenerator(_sql, "ItemCate01_" + GetMainForm().PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                            _report.UserID = GetMainForm().PODInfo.USER_ID;
                            ExcelFile exfile = _report.CreateReport();
                            ExcelFile file = exfile;
                            MemoryStream ms = new MemoryStream();
                            file.Save(ms);
                            FileDownloadGateway myDownload = new FileDownloadGateway() { Filename = "Item Category Tree - " + GetMainForm().PODInfo.Business_ID + ".xls" };
                            myDownload.Width = 500;
                            myDownload.SetContentType(FileDownloadGateway.DownloadContentType.MicrosoftExcel);
                            myDownload.StartBytesDownload(this, ms.ToArray());

                        }
                        break;
                    case "P":
                        if (dgvList.CurrentCell != null)
                        {
                            //DTO.OrganizationsInfo info = new DTO.OrganizationsInfo((DataRowView)dgvTVC_LOOKUPHVJ.CurrentRow.DataBoundItem);
                            //DataTable dt = DTO.OrganizationsInfo.ToDataTable();
                            //dt.Rows.Add(info.ToDataRow(dt));
                            //DataSet ds = new DataSet();
                            //ds.Tables.Add(dt);
                            //MainForm main = GetMainForm();
                            //if (main != null)
                            //    main.PrintDataSet(ds, _strType);
                        }
                        break;
                }
                _processStatus = strAction;
                if (sErr == "")
                    ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }



        protected override void refreshForm(string str)
        {
            txtCode.Text = "";
            txtDescription.Text = "";
            txtLookup.Text = "";
            cboStatus.Text = "";
        }

        protected override ErrorStatus validateForm(ref string sErr)
        {
            sErr = "";
            string sWarn = "";
            ErrorStatus result = ErrorStatus.SUCCESS;
            sErr = ValidItem();

            if (sErr != "") result = ErrorStatus.ERROR;
            else if (sWarn != "") result = ErrorStatus.WARNING;

            sErr = string.Format("{0}{1}", sErr, sWarn);

            return result;
        }

        private string ValidItem()
        {
            sErr = "";
            if (txtCode.Text == "")
            {
                sErr = "Coud not save blank Code, Please check!";
            }
            //else if (txtLookup.Text == "")
            //{
            //    sErr = "Coud not save blank Lookup, Please check!";
            //}
            return sErr;
        }

        protected override bool checkExists()
        {
            BUS.TVC_LOOKUPControl ctr = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            return ctr.IsExist(TB, TBField, txtCode.Text);
        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.TVC_LOOKUPControl ctr = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            DTO.TVC_LOOKUPInfo info = GetData();
            ctr.Add(info, ref sErr);
            return sErr;
        }

        protected override string updateRecord(bool isDraft = false)
        {
            BUS.TVC_LOOKUPControl ctr = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            DTO.TVC_LOOKUPInfo info = GetData();
            return ctr.Update(info);
        }

        protected override string delRecord()
        {
            BUS.TVC_LOOKUPControl ctr = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            return ctr.Delete(TB, TBField, txtCode.Text);
        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.TVC_LOOKUPInfo inf = new DTO.TVC_LOOKUPInfo((DataRowView)o);
                SetData(inf);
            }
        }

        protected override void enableForm(bool N)
        {
            foreach (Control x in tbdeatil.Controls)
            {
                if (x is TextBox || x is ComboBox || x is TVC.Modules.CustomControl.MultiColumnCombo)
                {
                    x.Enabled = N;
                }
            }
        }

        DataTable _dt = null;
        private void Categories_Load(object sender, EventArgs e)
        {


            refreshForm("");
            enableForm(false);
            gridFilter1.LoadData(GetMainForm().PODInfo.USER_ID, _strType, PODInfo.Business_ID);
            gridFilter1.panYear.Visible = false;
            gridFilter1.btnOK_Click(sender, e);
        }
        private void LoadTreeView(DataTable dtb)
        {
            //  DataTable dtFilter = gridFilter1.GetData();

            var tmp = dtb.AsEnumerable();

            //Filter

            var dt = tmp.GroupBy(r => new { maingroup = r["maingroup"], mainname = r["mainname"] })
                  .Select(g => new { maingroup = g.Key.maingroup, mainname = g.Key.mainname }).ToList();


            //tvCategory.Nodes.Clear();

            foreach (var xMain in dt)
            {
                TreeNode nMain = null;//tvCategory.Nodes.Add(string.Format("{0} - {1}", xMain.maingroup.ToString(), xMain.mainname.ToString()));
                nMain.NodeFont = new Font(this.Font, FontStyle.Bold);

                DTO.TVC_CATE2Info infMain = new DTO.TVC_CATE2Info(xMain.maingroup.ToString(), xMain.mainname.ToString());
                nMain.Tag = infMain;

                var dtSub = dtb.AsEnumerable()
                    .Where(r => r.Field<string>("maingroup") == (string)xMain.maingroup)
                    .Where(r => r.Field<string>("subgroup") != "")
                    .Select(r => new { maingroup = r["maingroup"], subgroup = r["subgroup"], subname = r["subname"] })
                    .GroupBy(g => new { g.maingroup, g.subgroup, g.subname })
                    .OrderBy(g => g.Key.subgroup)
                    //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                    .ToList();

                var dtSize = dtb.AsEnumerable()
                    .Where(r => r.Field<string>("maingroup") == (string)xMain.maingroup)
                    .Where(r => r.Field<string>("sizecode") != "")
                    .Select(r => new { maingroup = r["maingroup"], sizecode = r["sizecode"], sizename = r["sizename"] })
                    .GroupBy(g => new { g.maingroup, g.sizecode, g.sizename })
                    .OrderBy(g => g.Key.sizecode)
                    //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                    .ToList();

                var dtLen = dtb.AsEnumerable()
                    .Where(r => r.Field<string>("maingroup") == (string)xMain.maingroup)
                    .Where(r => r.Field<string>("lengthcode") != "")
                    .Select(r => new { maingroup = r["maingroup"], lengthcode = r["lengthcode"], lengthname = r["lengthname"] })
                    .GroupBy(g => new { g.maingroup, g.lengthcode, g.lengthname })
                    .OrderBy(g => g.Key.lengthcode)
                    //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                    .ToList();

                foreach (var subRow in dtSub)
                {
                    if ((string)subRow.Key.subgroup != "")
                    {
                        TreeNode nSub = nMain.Nodes.Add(string.Format("{0} - {1}", subRow.Key.subgroup, subRow.Key.subname));
                        DTO.TVC_CATE1Info infSub = new DTO.TVC_CATE1Info((string)xMain.maingroup, "1", (string)subRow.Key.subgroup, (string)subRow.Key.subname);
                        nSub.Tag = infSub;
                        foreach (var sizeRow in dtSize)
                        {
                            if ((string)sizeRow.Key.sizecode != "")
                            {
                                TreeNode nSize = nSub.Nodes.Add(string.Format("{0} - {1}", sizeRow.Key.sizecode, sizeRow.Key.sizename));
                                DTO.TVC_CATE1Info infSize = new DTO.TVC_CATE1Info((string)sizeRow.Key.maingroup, "2", (string)sizeRow.Key.sizecode, (string)sizeRow.Key.sizename);
                                nSize.Tag = infSize;
                                foreach (var lenRow in dtLen)
                                {
                                    TreeNode nLen = nSize.Nodes.Add(string.Format("{0} - {1}", lenRow.Key.lengthcode, lenRow.Key.lengthname));
                                    if ((string)lenRow.Key.lengthcode != "")
                                    {
                                        nLen.Tag = new DTO.TVC_CATE1Info((string)lenRow.Key.maingroup, "3", (string)lenRow.Key.lengthcode, (string)lenRow.Key.lengthname);
                                    }
                                }
                            }

                        }
                    }

                }
            }
        }


        private void SetData(DTO.TVC_LOOKUPInfo info)
        {
            txtCode.Text = info.Code;
            txtDescription.Text = info.Description;
            txtLookup.Text = info.Lookup;
            cboStatus.Text = info.Status;
            TB = info.TB;
            TBField = info.TBField;
        }


        private DTO.TVC_LOOKUPInfo GetData()
        {
            return new DTO.TVC_LOOKUPInfo(TB, TBField, txtCode.Text, txtLookup.Text, txtDescription.Text, cboStatus.Text);

        }

        private void gridFilter1_GridFiterEvent(string strFilter, int year)// filter
        {
            string sErr = "";
            BUS.TVC_LOOKUPControl ctrLo = new BUS.TVC_LOOKUPControl(PODInfo.Business_ID);
            _dtb = ctrLo.GetSearch(strFilter, TBField, ref sErr);

            bisCategories.DataSource = _dtb;

            BUS.TVC_CATEControl MMQCtr = new BUS.TVC_CATEControl();
            _dt = MMQCtr.GetbyFilter(GetMainForm().PODInfo.Business_ID, strFilter, ref sErr);

            BuildCategoryListView(lvCate);
            FillCateListView(lvCate);

        }

        #region Method
        private void BuildCategoryListView(Gizmox.WebGUI.Forms.ListView lv)
        {
            //lv.BorderStyle = BorderStyle.None;
            lv.HeaderStyle = ColumnHeaderStyle.None;
            lv.Items.Clear();
            lv.Columns.Clear();
            ColumnHeader ch = null;
            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 16;
            ch.Type = ListViewColumnType.Control;
            ch.PreferedItemHeight = 16;
            lv.Columns.Add(ch);

            ch = null;
            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 60;
            ch.Type = ListViewColumnType.Control;
            ch.PreferedItemHeight = 16;
            lv.Columns.Add(ch);

            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 700;
            ch.Type = ListViewColumnType.Control;
            lv.Columns.Add(ch);
        }

        private void FillCateListView(Gizmox.WebGUI.Forms.ListView lv)
        {
            var tmp = _dt.AsEnumerable();
            var dt = tmp.Where(r => r["subgroup"] != "")
                .GroupBy(r => new { maingroup = r["maingroup"].ToString(), mainname = r["mainname"].ToString(), subgroup = r["subgroup"].ToString(), subname = r["subname"].ToString() })
                  .Select(g => new { maingroup = g.Key.maingroup, mainname = g.Key.mainname, subgroup = g.Key.subgroup, subname = g.Key.subname }).ToList();

            foreach (var row in dt)
            {
                Panel pnl = new Panel();
                pnl.DockPadding.Left = 20;
                ListViewPanelItem lvpi = new ListViewPanelItem(pnl);
                pnl.Height = 200;

                PictureBox pb = new PictureBox();
                pb.Size = new Size(16, 16);
                pb.Tag = lvpi;
                pb.Click += new EventHandler(CateItem_Click);
                lvpi.SubItems.Add(pb);

                Label lbl = new Label();
                lbl.AutoSize = true;
                lbl.Cursor = Gizmox.WebGUI.Forms.Cursors.Hand;
                lbl.Tag = lvpi;
                lbl.Font = new Font(this.Font, FontStyle.Bold);
                lbl.Click += new EventHandler(CateItem_Click);
                lbl.Text = row.maingroup + row.subgroup;                
                lvpi.SubItems.Add(lbl);



                lbl = new Label();
                lbl.Font = new Font(this.Font, FontStyle.Bold);
                lbl.Text = row.mainname + " - " + row.subname;
                lbl.Click += new EventHandler(CateItem_Click);
                lbl.AutoSize = false;
                lbl.Height = 16;
                lbl.Width = 700;
                lbl.Tag = lvpi;
                lbl.Cursor = Gizmox.WebGUI.Forms.Cursors.Hand;
                lvpi.SubItems.Add(lbl);

                lv.Items.Add(lvpi);

                RowTag rowTag = new RowTag();
                rowTag.ID = row.maingroup + "|" + row.subgroup;
                rowTag.rowExpansion = RowExpansionType.Expanded;
                rowTag.label = lbl;
                rowTag.pictureBox = pb;
                lvpi.Tag = rowTag;

                ToggleCateRowExpansion(lvpi);
            }
        }
        private Gizmox.WebGUI.Forms.ListView BuildSizeListView()
        {
            Gizmox.WebGUI.Forms.ListView lv = new Gizmox.WebGUI.Forms.ListView();
            lv.BorderStyle = BorderStyle.None;
            lv.HeaderStyle = ColumnHeaderStyle.None;
            lv.Scrollable = false;
            lv.FullRowSelect = true;

            ColumnHeader ch = null;
            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 50;
            ch.Type = ListViewColumnType.Text;
            ch.PreferedItemHeight = 50;
            lv.Columns.Add(ch);

            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 250;
            ch.Type = ListViewColumnType.Text;
            lv.Columns.Add(ch);

            ch = null;
            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 30;
            ch.Type = ListViewColumnType.Text;
            ch.PreferedItemHeight = 50;
            lv.Columns.Add(ch);

            ch = new ColumnHeader();
            ch.Text = "";
            ch.Width = 250;
            ch.Type = ListViewColumnType.Text;
            lv.Columns.Add(ch);

            return lv;
        }
        private void FillSizeListView(ListViewPanelItem lvpi, Gizmox.WebGUI.Forms.ListView lvSub, string customerID)
        {
            var tmp = _dt.AsEnumerable();
            string mainGroup = "", subGroup = "";
            mainGroup = customerID.Split('|')[0];
            subGroup = customerID.Split('|')[1];

            var dtSize = tmp.Where(r => r.Field<string>("maingroup") == mainGroup)
                .Where(r => r.Field<string>("sizecode") != "" || r.Field<string>("lengthcode") != "")
                .Select(r => new { rowrank = r["rowrank"], sizecode = r["sizecode"].ToString(), sizename = r["sizename"].ToString(), lengthcode = r["lengthcode"].ToString(), lengthname = r["lengthname"].ToString() })
                .OrderBy(r => r.rowrank)
                //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                .ToList();

            lvpi.Panel.Height = 0;
            int cnt = 0;

            lvSub.Items.Clear();

            foreach (var row in dtSize)
            {
                ListViewItem lvi = new ListViewItem();

                lvi.SubItems.Add(row.sizecode);
                lvi.SubItems.Add(row.sizename);
                lvi.SubItems.Add(row.lengthcode);
                lvi.SubItems.Add(row.lengthname);

                lvSub.Items.Add(lvi);
                cnt += 1;

            }
            lvpi.Panel.Height = cnt * 17;
        }

        private void ToggleCateRowExpansion(ListViewPanelItem lvpi)
        {
            RowTag rowTag = (RowTag)lvpi.Tag;

            if (rowTag.rowExpansion == RowExpansionType.Collapsed)
            {
                rowTag.label.ForeColor = Color.Red;
                rowTag.pictureBox.Image = new IconResourceHandle("expanded.png");
                lvpi.Panel.Visible = true;

                rowTag.rowExpansion = RowExpansionType.Expanded;


                Gizmox.WebGUI.Forms.ListView lvSub = null;
                if (lvpi.Panel.Controls.Count == 0)
                {
                    lvSub = BuildSizeListView();
                    lvpi.Panel.Controls.Add(lvSub);
                    lvSub.Dock = DockStyle.Fill;
                }
                else
                {
                    lvSub = (Gizmox.WebGUI.Forms.ListView)lvpi.Panel.Controls[0];
                }

                FillSizeListView(lvpi, lvSub, rowTag.ID);
            }
            else
            {
                rowTag.label.ForeColor = rowTag.label.ForeColor = System.Drawing.Color.FromArgb(24, 134, 231);
                rowTag.pictureBox.Image = new IconResourceHandle("collapsed.png");
                lvpi.Panel.Visible = false;
                rowTag.rowExpansion = RowExpansionType.Collapsed;
            }

            lvpi.Tag = rowTag;
        }

        void CateItem_Click(object sender, EventArgs e)
        {
            ListViewPanelItem lvpi = null;

            if (sender is PictureBox) lvpi = (ListViewPanelItem)((PictureBox)sender).Tag;
            else if (sender is Label) lvpi = (ListViewPanelItem)((Label)sender).Tag;

            ToggleCateRowExpansion(lvpi);
        }

        #region enumerations
        public enum RowExpansionType
        {
            Expanded,
            Collapsed
        }
        #endregion enumerations

        #region structs
        public struct RowTag
        {
            public string ID;
            public ListViewPanelItem container;
            public RowExpansionType rowExpansion;
            public Label label;
            public PictureBox pictureBox;
        }
        #endregion structs

        private void btExpand_Click(object sender, EventArgs e)
        {
            ExpandAllCates(lvCate);
        }
        #endregion

        private void btCollapse_Click(object sender, EventArgs e)
        {
            CollapseAllCates(lvCate);

        }
        private void CollapseAllCates(ListView clvpi)
        {
            foreach (ListViewPanelItem lvpi in clvpi.Items)
            {
                if (((RowTag)lvpi.Tag).rowExpansion == RowExpansionType.Expanded)
                {
                    ToggleCateRowExpansion(lvpi);
                }
            }
        }
        private void ExpandAllCates(ListView clvpi)
        {
            foreach (ListViewPanelItem lvpi in clvpi.Items)
            {
                if (((RowTag)lvpi.Tag).rowExpansion == RowExpansionType.Collapsed)
                {
                    ToggleCateRowExpansion(lvpi);
                }
            }
        }

    }
}